package com.qingdai.shopcenter.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.qingdai.business.emuns.*;
import com.qingdai.business.entities.CommonResult;
import com.qingdai.business.service.CommodityService;
import com.qingdai.business.service.ShopService;
import com.qingdai.business.service.UserRoleService;
import com.qingdai.business.service.UserService;
import com.github.yulichang.query.MPJQueryWrapper;
import com.qingdai.business.utils.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author LiuZiMing
 * @since 2024-01-26
 */
@RestController
@RequestMapping("/shop")
@Tag(name = "店铺")
public class ShopController {
    @Resource
    private ShopService shopService;
    @DubboReference
    private UserService userService;
    @DubboReference
    private CommodityService commodityService;
    @DubboReference
    private UserRoleService userRoleService;
    @Resource
    private JwtUtil jwtUtil;

    @GetMapping("/xyz")
    @Operation(summary = "获取所有商店", description = "获取所有商店")
    @Parameters({
//            @Parameter(name = "id", description = "id", required = true),
    })
    private CommonResult<List<Shop>> getAllShop() {
        List<Shop> list = shopService.list();
        return new CommonResult<>(200, "获取所有商店成功", list);
    }

    @GetMapping("/jwt")
    @Operation(summary = "获取本人商店", description = "获取本人商店")
    @Parameters({
//            @Parameter(name = "id", description = "id", required = true),
    })
    private CommonResult<List<Shop>> getShopByJwt(HttpServletRequest request) {
        CommonResult userIdByJwtCommonResult = jwtUtil.getUserIdByRequest(request);
        Integer userIdByJwt = (Integer) userIdByJwtCommonResult.getData();
        MPJQueryWrapper mpjQueryWrapper = new MPJQueryWrapper();
        mpjQueryWrapper.select("*").eq("seller_id", userIdByJwt);
        List<Shop> list = shopService.list(mpjQueryWrapper);
        return new CommonResult<>(200, "获取本人所有商店成功", list);
    }

    @PostMapping("/jwt")
    @Operation(summary = "创建新商店", description = "创建新商店")
    @Parameters({
//            @Parameter(name = "id", description = "id", required = true),
            @Parameter(name = "name", description = "店名", required = true),
    })
    public CommonResult createShopByJwt(@RequestParam(required = true) String name,
                                        HttpServletRequest request) {
        CommonResult result = jwtUtil.getUserIdByRequest(request);
        Integer jwtUserId = (Integer) result.getData();
        boolean createResult = shopService.save(new Shop(null, name, 0.0, 5.0, jwtUserId, null));
        boolean changeUserRoleResult = userRoleService.saveOrUpdate(new UserRole(jwtUserId, 4));
        if (createResult&&changeUserRoleResult) {
            return new CommonResult(200, "创建商店成功");
        } else {
            return new CommonResult(400, "创建商店失败");
        }
    }

    @GetMapping("/id")
    @Operation(summary = "根据id获取商店", description = "根据id获取商店")
    @Parameters({
            @Parameter(name = "id", description = "id", required = true),
    })
    private CommonResult<Shop> getShopById(Integer id) {
//        CommonResult userIdByJwtCommonResult = jwtUtil.getUserIdByJwt(request);
//        Integer userIdByJwt = (Integer) userIdByJwtCommonResult.getData();
        Shop shop = shopService.getById(id);

        return new CommonResult<>(200, "根据id获取商店成功", shop);
    }

    @PutMapping("/jwt/id")
    @Operation(summary = "根据id更改商店(店名,卖家)", description = "根据id更改商店(店名,卖家)")
    @Parameters({@Parameter(name = "id", description = "id", required = true),
            @Parameter(name = "name", description = "昵称", required = false),
    })
    public CommonResult updateShopByIdAndJwt(@RequestParam(required = true) Integer id,
                                             @RequestParam(required = false) String name,
                                             @RequestParam(required = false) Integer sellerId,
                                             HttpServletRequest request) {
        CommonResult result = jwtUtil.getUserIdByRequest(request);
        Integer jwtUserId = (Integer) result.getData();
        Shop shop = shopService.getById(id);
        if (shop == null) {
            return new CommonResult(400, "id非法");
        } else if (Objects.equals(shop.getSellerId(), jwtUserId)) {
            User user = userService.getUserByUserId(sellerId);
            if (user == null) {
                return new CommonResult(200, "userId非法");
            } else {
                boolean createResult = shopService.save(new Shop(null, name, null, 5.0, sellerId, null));
                if (createResult) {
                    return new CommonResult(200, "修改商店成功");
                } else {
                    return new CommonResult(400, "修改商店失败");
                }
            }
        } else {
            return new CommonResult(400, "请勿修改他人商店");
        }
    }

    @DeleteMapping("/jwt/id")
    @Operation(summary = "根据id删除商店", description = "根据id删除商店")
    @Parameters({
            @Parameter(name = "id", description = "id", required = true),
    })
    public CommonResult deleteShopByIdAndJwt(@RequestParam(required = true) Integer id,
                                             HttpServletRequest request) {
        CommonResult result = jwtUtil.getUserIdByRequest(request);
        Integer jwtUserId = (Integer) result.getData();
        Shop shop = shopService.getById(id);
        if (shop == null) {
            return new CommonResult(400, "id非法");
        }
        if (!Objects.equals(shop.getSellerId(), jwtUserId)) {
            return new CommonResult(400, "请勿删除他人商店");
        }
        try {
            boolean deleteShopResult = shopService.removeById(id);
            if (!deleteShopResult) {
                throw new Exception("删除商店失败");
            }
        } catch (Exception exception) {
            return new CommonResult(400, "删除商店失败");
        }
        MPJQueryWrapper<Commodity> mpjQueryWrapper = new MPJQueryWrapper<Commodity>();
        mpjQueryWrapper.eq("shop_id", id);
        try {
            boolean deleteCommodityResult = commodityService.remove(mpjQueryWrapper);
            if (!deleteCommodityResult) {
                throw new Exception("删除商店失败(商品删除失败)");
            }
        } catch (Exception exception) {
            return new CommonResult(400, "删除商店失败(商品删除失败)");
        }
        try {
            boolean changeUserRoleResult = userRoleService.saveOrUpdate(new UserRole(jwtUserId, 3));
            if (!changeUserRoleResult) {
                throw new Exception("删除商店失败(用户身份改变失败)");
            }
        } catch (Exception exception) {
            return new CommonResult(400, "删除商店失败(用户身份改变失败)");
        }
        return new CommonResult(200, "删除商店成功");

    }

}